import {
  Controller,
  Get,
  Post,
  Query,
  Body,
  Patch,
  Delete,
  UseGuards,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { BlogService } from './blog.service';
import {
  ApiResponse,
  ApiOperation,
  ApiTags,
  ApiBearerAuth,
} from '@nestjs/swagger';
import { Search, SearchParams } from 'src/common/decorators/search.decorator';

import { BlogEntity } from './entities/blog.entity';
import { CreateBlogDto } from './dto/create-blog.dto';
import { UpdateBlogDto } from './dto/update-blog.dto';
import { ListBlogDto, ListBlogReturn } from './dto/list-blog.dto';
import { JwtAuthGuard } from '@/common/guards/jwt.guard';

@ApiTags('博客模块')
@ApiBearerAuth()
@Controller('blog')
@UseGuards(JwtAuthGuard)
export class BlogController {
  constructor(private readonly blogService: BlogService) {}

  @Post()
  @ApiOperation({ summary: '创建博客' })
  @ApiResponse({ type: BlogEntity })
  create(@Body() createBlogDto: CreateBlogDto) {
    return this.blogService.create(createBlogDto);
  }

  @Get('list')
  @ApiOperation({ summary: '查询博客列表' })
  @ApiResponse({ type: ListBlogReturn })
  findAll(
    @Query() searchDto: ListBlogDto,
    @SearchParams() searchParams: Search,
  ): Promise<ListBlogReturn> {
    return this.blogService.findAll(searchParams);
  }

  @Get()
  @ApiOperation({ summary: '查询博客详情' })
  @ApiResponse({ type: BlogEntity })
  async findOne(@Query('id') id: string): Promise<BlogEntity> {
    const blogItem = await this.blogService.findOne(id);
    if (!blogItem) {
      throw new HttpException('未找到该博客', HttpStatus.BAD_REQUEST);
    }
    blogItem.visited += 1;
    this.blogService.update(id, blogItem);
    return blogItem;
  }

  @Patch()
  @ApiOperation({ summary: '更新博客' })
  @ApiResponse({ example: 'success' })
  update(@Body('id') id: string, @Body() updateBlogDto: UpdateBlogDto) {
    updateBlogDto.length = updateBlogDto.content.length;
    return this.blogService.update(id, updateBlogDto);
  }

  @Delete()
  @ApiOperation({ summary: '删除博客' })
  @ApiResponse({ example: 'success' })
  remove(@Body('id') id: string) {
    return this.blogService.remove(id);
  }
}
